package com.jin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jin.common.ResponseResult;
import com.jin.service.AddGroup;
import com.jin.service.UpdateGroup;
import com.jin.bean.User;
import com.jin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //获取全部用户
    @GetMapping("/all")
    public ResponseResult<List<User>> getAllUsers() {
        List<User> users = userService.list();
        return ResponseResult.success( "获取全部用户成功", users);
    }

    // 获取所有用户（带分页）
    @GetMapping("/list")
    public ResponseResult<List<User>> list(@RequestParam(defaultValue = "1") int pageNum,
                                           @RequestParam(defaultValue = "10") int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        List<User> records = userService.page(page).getRecords();
        long total = userService.page(page).getTotal();
        return ResponseResult.success("获取所有用户（带分页）成功", records,total);
    }

    // 根据ID获取用户信息
    @GetMapping("/{id}")
    public ResponseResult<User> getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return ResponseResult.fail("未找到该用户", null);
        }
        return ResponseResult.success( "成功找到该用户", user);
    }

    //  添加用户
    @PostMapping
    public ResponseResult<Boolean> addUser(@RequestBody @Validated(AddGroup.class) User user,
                                           @RequestParam(required = false) Boolean isAdmin) {
        try {
            // 如果是注册行为，强制设置 isAdmin 为 false
            if (isAdmin == null || !isAdmin) {
                user.setAdmin(false);
            }

            boolean result = userService.addUser(user);
            return new ResponseResult<>(result ? 0 : 1, result ? "操作成功" : "操作失败", result, null);
        } catch (RuntimeException e) {
            return ResponseResult.fail( e.getMessage(), false);
        }
    }


    // 更新用户
    @PutMapping
    public ResponseResult<Boolean> update(@RequestBody @Validated(UpdateGroup.class) User user) {
        boolean result = userService.updateUser(user);
        return new ResponseResult<>(result ? 0 : 1, result ? "更新成功" : "更新失败", result, null);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable Integer id) {
        boolean result = userService.deleteUser(id);
        return new ResponseResult<>(result ? 0 : 1, result ? "删除成功" : "删除失败", result, null);
    }


    // 用户登录
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> response = new HashMap<>();

        if (!userService.checkUserExists(username)) {
            response.put("success", false);
            response.put("message", "用户名不存在");
            return ResponseResult.fail("用户名不存在", response);
        }

        User user = userService.getUserByUsername(username);

        if (passwordEncoder.matches(password, user.getPassword())) {
            response.put("success", true);
            response.put("isAdmin", user.isAdmin());
            response.put("userId", user.getId());
            response.put("unitId", user.getUnitId());
            response.put("message", "用户名与密码正确");
            return ResponseResult.success("登录成功 ",response);
        } else {
            response.put("success", false);
            response.put("message", "用户名或密码错误");
            return ResponseResult.fail("登录失败", response);
        }
    }

    // 用户密码重置(不检查旧密码)
    @PostMapping("/reset-password")
    public ResponseResult<Boolean> resetPassword(
            @RequestParam String newPassword,
            @RequestParam String username) {
        // 验证用户是否存在
        if (!userService.checkUserExists(username)) {
            return ResponseResult.fail("用户不存在", false);
        }
        // 修改密码
        boolean result = userService.resetPassword(username, newPassword);
        return new ResponseResult<>(result ? 0 : 1, result ? "密码修改成功" : "密码修改失败", result, null);
    }

    // 修改密码
    @PostMapping("/change-password")
    public ResponseResult<Boolean> changePassword(@RequestParam String username,
                                                  @RequestParam String oldPassword,
                                                  @RequestParam String newPassword) {
        // 验证用户是否存在
        if (!userService.checkUserExists(username)) {
            return ResponseResult.fail( "用户不存在", false);
        }

        // 验证原密码是否正确
        User user = userService.getUserByUsername(username);
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return ResponseResult.fail("原密码不正确", false);
        }

        // 修改密码
        boolean result = userService.resetPassword(username, newPassword);
        return new ResponseResult<>(result ? 0 : 1, result ? "密码修改成功" : "密码修改失败", result,null);
    }

    // 启用用户
    @PutMapping("/enable/{id}")
    public ResponseResult<Boolean> enable(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return ResponseResult.fail("未找到该用户", false);
        }
        user.setIsEnable(true); // 启用
        boolean result = userService.updateById(user);
        return new ResponseResult<>(result ? 0 : 1, result ? "启用成功" : "启用失败", result, null);
    }

    // 禁用用户
    @PutMapping("/disable/{id}")
    public ResponseResult<Boolean> disable(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return ResponseResult.fail("未找到该用户", false);
        }
        user.setIsEnable(false);//  禁用
        boolean result = userService.updateById(user);
        return new ResponseResult<>(result ? 0 : 1, result ? "禁用成功" : "禁用失败", result, null);
    }

    // 检查用户名是否存在
    @GetMapping("/check")
    public ResponseResult<Boolean> checkUsername(@RequestParam String username) {
        boolean result = userService.checkUserExists(username);
        return new ResponseResult<>(result ? 0 : 1, result ? "用户名已存在" : "用户名可用", result, null);
    }
    //  获取默认用户
    @GetMapping("/default")
    public ResponseResult<User> getDefaultUserById() {
        User user = new User();
        user.setUsername("default");
        user.setPassword(passwordEncoder.encode("default"));
        user.setAdmin(false);
        user.setIsEnable(false);
        user.setRegisterTime(new Date());
        user.setUnitId(1);
        return ResponseResult.success("操作成功", user);
    }
    //按名称模糊查询
    @GetMapping("/search")
    public ResponseResult<List<User>> searchByName(@RequestParam String username) {
        List<User> users = userService.list(new QueryWrapper<User>().like("username", username));
        return ResponseResult.success("操作成功", users);
    }
}